<script setup>
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock, Key, UserFilled, Message } from '@element-plus/icons-vue'
import { useAuthStore } from '@/store'

const router = useRouter()
const registerFormRef = ref()
const loading = ref(false)

const authStore = useAuthStore()

// 注册方式选择（密码/验证码）
const registerType = ref('password') // 默认密码注册
const isPasswordRegister = computed(() => registerType.value === 'password')

// 表单数据 - 密码注册
const registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  agreedTerms: false
})

// 表单数据 - 验证码注册
const codeRegisterForm = reactive({
  email: '',
  verifyCode: '',
  agreedTerms: false
})

// 验证码相关
const countdown = ref(0)
const isSending = ref(false)
let timer = null

// 自定义校验函数：确认密码
const validateConfirmPassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== registerForm.password) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

// 自定义校验函数：用户协议
const validateAgreement = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请阅读并同意用户协议和隐私政策'))
  } else {
    callback()
  }
}

// 表单验证规则 - 密码注册
const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度应在3-20个字符之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度应在6-20个字符之间', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: validateConfirmPassword, trigger: 'blur' }
  ],
  agreedTerms: [
    { validator: validateAgreement, trigger: 'change' }
  ]
}

// 表单验证规则 - 验证码注册
const codeRegisterRules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  verifyCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码长度应为6位', trigger: 'blur' }
  ],
  agreedTerms: [
    { validator: validateAgreement, trigger: 'change' }
  ]
}

// 切换注册方式
const switchRegisterType = (type) => {
  registerType.value = type
}

// 发送验证码
const sendVerifyCode = async () => {
  // 验证邮箱格式
  if (!codeRegisterForm.email) {
    ElMessage.warning('请先输入邮箱')
    return
  }
  
  const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
  if (!emailPattern.test(codeRegisterForm.email)) {
    ElMessage.warning('请输入正确的邮箱格式')
    return
  }
  
  isSending.value = true
  try {
    // 调用发送验证码API
    await authStore.sendCode(codeRegisterForm.email)
    
    // 开始倒计时
    countdown.value = 60
    timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timer)
        isSending.value = false
      }
    }, 1000)
  } catch (error) {
    isSending.value = false
  }
}

const handleRegister = async () => {
  const formRef = registerFormRef.value
  if (!formRef) return
  
  // 根据注册类型选择不同的表单验证和注册逻辑
  if (isPasswordRegister.value) {
    // 密码注册
    await formRef.validate(async (valid, fields) => {
      if (valid) {
        loading.value = true
        
        try {
          // 创建注册数据对象
          const userData = {
            username: registerForm.username,
            password: registerForm.password
          }
          
          // 使用 authStore 进行注册
          const success = await authStore.registerUser(userData)
          
          if (success) {
            ElMessage.success('注册账号成功')
            router.push('/')
          }
        } finally {
          loading.value = false
        }
      } else {
        console.log('验证失败', fields)
      }
    })
  } else {
    // 验证码注册
    await formRef.validate(async (valid, fields) => {
      if (valid) {
        loading.value = true
        
        try {
          // 创建注册数据对象
          const userData = {
            email: codeRegisterForm.email,
            code: codeRegisterForm.verifyCode
          }
          
          // 使用 authStore 进行验证码注册
          const success = await authStore.registerWithEmailCode(userData)
          
          if (success) {
            ElMessage.success('注册账号成功')
            router.push('/')
          }
        } finally {
          loading.value = false
        }
      } else {
        console.log('验证失败', fields)
      }
    })
  }
}
</script>

<template>
  <div class="register-container">
    <div class="register-box">
      <div class="register-header">
        <div class="title-icon">
          <el-icon :size="30" color="#c20c0c"><UserFilled /></el-icon>
        </div>
        <h1>创建账号</h1>
        <div class="title-decoration"></div>
        <p>加入我们，探索更多音乐世界</p>
      </div>
      
      <!-- 注册方式选择器 -->
      <div class="register-type-selector">
        <div 
          class="register-type-option" 
          :class="{ active: isPasswordRegister }"
          @click="switchRegisterType('password')"
        >
          普通注册
        </div>
        <div 
          class="register-type-option" 
          :class="{ active: !isPasswordRegister }"
          @click="switchRegisterType('code')"
        >
          邮箱注册
        </div>
      </div>

      <!-- 密码注册表单 -->
      <el-form 
        v-if="isPasswordRegister"
        ref="registerFormRef" 
        :model="registerForm" 
        :rules="registerRules" 
        class="register-form"
      >
        <el-form-item prop="username">
          <el-input 
            v-model="registerForm.username" 
            placeholder="请输入用户名"
            :prefix-icon="User"
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input 
            v-model="registerForm.password" 
            type="password" 
            placeholder="请输入密码"
            :prefix-icon="Lock"
            show-password
          />
        </el-form-item>

        <el-form-item prop="confirmPassword">
          <el-input 
            v-model="registerForm.confirmPassword" 
            type="password" 
            placeholder="请确认密码"
            :prefix-icon="Key"
            show-password
          />
        </el-form-item>

        <el-form-item prop="agreedTerms">
          <el-checkbox 
            v-model="registerForm.agreedTerms" 
            class="custom-checkbox"
          >
            我同意<a href="#" class="terms-link">用户协议</a>和<a href="#" class="terms-link">隐私政策</a>
          </el-checkbox>
        </el-form-item>

        <el-button 
          type="danger" 
          class="register-button" 
          @click="handleRegister" 
          :loading="loading"
        >
          注册
        </el-button>
      </el-form>
      
      <!-- 验证码注册表单 -->
      <el-form 
        v-else
        ref="registerFormRef" 
        :model="codeRegisterForm" 
        :rules="codeRegisterRules" 
        class="register-form"
      >
        <el-form-item prop="email">
          <el-input 
            v-model="codeRegisterForm.email" 
            placeholder="请输入邮箱"
            :prefix-icon="Message"
          />
        </el-form-item>
        
        <el-form-item prop="verifyCode">
          <div class="code-input-group">
            <el-input
              v-model="codeRegisterForm.verifyCode"
              placeholder="请输入验证码"
              :prefix-icon="Key"
            />
            <el-button 
              class="code-button" 
              :disabled="isSending || countdown > 0"
              @click="sendVerifyCode"
            >
              {{ countdown > 0 ? `${countdown}秒后重新获取` : '获取验证码' }}
            </el-button>
          </div>
        </el-form-item>

        <!-- 添加帮助链接 -->
        <div class="form-help">
          <a href="#" class="help-link">收不到验证码？</a>
        </div>

        <el-form-item prop="agreedTerms">
          <el-checkbox 
            v-model="codeRegisterForm.agreedTerms" 
            class="custom-checkbox"
          >
            我同意<a href="#" class="terms-link">用户协议</a>和<a href="#" class="terms-link">隐私政策</a>
          </el-checkbox>
        </el-form-item>

        <el-button 
          type="danger" 
          class="register-button" 
          @click="handleRegister" 
          :loading="loading"
        >
          注册
        </el-button>
      </el-form>

      <div class="login-link">
        已有账号？<router-link to="/login">返回登录</router-link>
      </div>
    </div>
  </div>
</template>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20px;
}

.register-box {
  width: 100%;
  max-width: 420px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  padding: 30px;
}

/* 注册方式选择器样式 */
.register-type-selector {
  display: flex;
  margin-bottom: 25px;
  border-bottom: 1px solid #eee;
}

.register-type-option {
  flex: 1;
  text-align: center;
  padding: 10px 0;
  cursor: pointer;
  font-size: 14px;
  color: #666;
  position: relative;
  transition: all 0.3s;
}

.register-type-option.active {
  color: #c20c0c;
}

.register-type-option.active::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 20%;
  width: 60%;
  height: 2px;
  background-color: #c20c0c;
}

.register-type-option:hover {
  color: #c20c0c;
}

/* 验证码输入框组样式 */
.code-input-group {
  display: flex;
  gap: 10px;
  width: 100%; /* 确保占据整行宽度 */
}

.code-input-group .el-input {
  flex: 1;
}

.code-button {
  width: 120px;
  flex-shrink: 0; /* 防止按钮被压缩 */
  font-size: 12px;
  padding: 0 5px;
  background-color: #fff;
  border-color: #d9d9d9;
  color: #606266;
}

.code-button:hover, .code-button:focus {
  background-color: #fef0f0;
  border-color: #f56c6c;
  color: #c20c0c;
  transition: all 0.3s;
}

.code-button:disabled {
  background-color: #f5f5f5;
  border-color: #e4e7ed;
  color: #c0c4cc;
}

.register-header {
  text-align: center;
  margin-bottom: 35px;
  position: relative;
}

.title-icon {
  background-color: #fef0f0;
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 0 auto 15px;
  box-shadow: 0 3px 6px rgba(194, 12, 12, 0.1);
}

.register-header h1 {
  font-size: 28px;
  margin-bottom: 15px;
  color: #333;
  font-weight: 600;
}

.title-decoration {
  width: 40px;
  height: 3px;
  background-color: #c20c0c;
  margin: 0 auto 15px;
  border-radius: 3px;
}

.register-header p {
  color: #666;
  font-size: 14px;
}

.register-form :deep(.el-input__wrapper) {
  padding: 1px 11px;
}

.register-form :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #c20c0c inset;
}

.register-form :deep(.el-form-item) {
  margin-bottom: 20px;
}

.register-form :deep(.el-form-item__error) {
  color: #c20c0c;
}

.custom-checkbox {
  --el-checkbox-font-size: 14px;
  --el-checkbox-checked-text-color: #333;
  /* --el-checkbox-checked-icon-color: #c20c0c; */
  --el-checkbox-checked-bg-color: #fff;
  --el-checkbox-checked-border-color: #c20c0c;
}

.terms-link {
  color: #c20c0c;
  text-decoration: none;
}

.register-button {
  width: 100%;
  padding: 12px;
  margin-bottom: 20px;
  background-color: #c20c0c;
  border-color: #c20c0c;
}

.register-button:hover, .register-button:focus {
  background-color: #a60a0a;
  border-color: #a60a0a;
}

.login-link {
  text-align: center;
  font-size: 14px;
  color: #666;
}

.login-link a {
  color: #c20c0c;
  text-decoration: none;
}

/* 帮助链接样式 */
.form-help {
  text-align: right;
  margin-bottom: 15px;
}

.help-link {
  color: #c20c0c;
  text-decoration: none;
  font-size: 13px;
}

.help-link:hover {
  text-decoration: underline;
}
</style> 